package com.hpsk.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hpsk.utils.CommonServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author huangwang2832511019
 */
@Slf4j
public class CommonPageRequest {

    private static final Integer DEFAULT_PAGE_SIZE = 10;
    private static final Integer DEFAULT_PAGE_PAGE = 1;
    private static final Integer MAX_PAGE_SIZE = 500;
    public static <T> IPage<T> defaultPage(){
        return defaultPage(new ArrayList<>());
    }
    /**
     * 从请求头中获取分页信息
     *
     * @return 分页对象
     */
    public static <T> IPage<T> defaultPage(List<T> requestList) {
        HttpServletRequest request = CommonServletUtil.getRequest();
        String pageSizeStr = request.getHeader("X-Page-Size");
        String pageStr = request.getHeader("X-Page-Current");

        int pageSize = DEFAULT_PAGE_SIZE;
        int page = DEFAULT_PAGE_PAGE;

        if (pageSizeStr != null) {
            try {
                pageSize = Integer.parseInt(pageSizeStr);
                if (pageSize > MAX_PAGE_SIZE) {
                    pageSize = MAX_PAGE_SIZE;
                }
            } catch (NumberFormatException e) {
                // 无效的页大小，使用默认值
                throw new CommonException("无效的页大小");
            }
        }

        if (pageStr != null) {
            try {
                page = Integer.parseInt(pageStr);
                if (page < 1) {
                    page = DEFAULT_PAGE_PAGE;
                }
            } catch (NumberFormatException e) {
                // 无效的页码，使用默认值
                throw new CommonException("无效的页码");
            }
        }
        Page<T> objectPage = new Page<>(page, pageSize);
        objectPage.setRecords(requestList);
        return objectPage;
    }
}
